require 'digest/sha1'
class Employee < ActiveRecord::Base
  belongs_to :gender
  has_many :meetings
  belongs_to :department
  belongs_to :position
  belongs_to :level
  has_many :leaves
  has_many :leave_offices
  belongs_to :attendance_working_hour
  has_many :attendances
   has_many :write_boards

validates_presence_of :name,:on => :create
validates_presence_of :email,:on => :create
#validates_presence_of :role_level_id,:on => :create
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "is invalid" , :on => :create
validates_uniqueness_of :email,:on => :create
validates_presence_of :password,:on => :create, :if => :new_user_register
validates_presence_of :password_confirmation,:on => :create, :if => :new_user_register
validates_confirmation_of :password,:on => :create, :if => :new_user_register
validates_length_of :password, :within => 6..12,:on => :create, :if => :new_user_register

#validates_presence_of :password,:on => :update
#validates_presence_of :password_confirmation,:on => :update
#validates_confirmation_of :password,:on => :update
#validates_length_of :password, :within => 6..12,:on => :update


#protected
def new_user_register
Employee.find_by_id(self.id)
end



attr_protected :id, :salt

attr_accessor :password, :password_confirmation

def self.authenticate(email, pass)
    u=find(:first, :conditions=>["email = ?", email])
    return nil if u.nil?
    return u if Employee.encrypt(pass, u.salt)==u.hashed_password
    nil
  end  

  def password=(pass)
    @password=pass
    @cibai = self.email
    self.salt = Employee.random_string(10) if !self.salt?
    self.hashed_password = Employee.encrypt(@password, self.salt)
    #self.verification = Employee.encrypt(@cibai, self.salt)
  end


def send_new_password
    new_pass = Employee.random_string(10)
    self.password = self.password_confirmation = new_pass
    self.save
    mail_info = {"name" => self.name, "user_email" => self.email, "new_pass" => new_pass}
    Notifier.deliver_send_my_password(mail_info)
end

def send_my_new_password
    new_pass = Employee.random_string(10)
    self.password = self.password_confirmation = new_pass
    self.save
    mail_info = {"name" => self.name, "user_email" => self.email, "new_pass" => new_pass}
    #Notifier.deliver_send_forgot_user_password(mail_info)
end


protected

def self.encrypt(pass, salt)
  Digest::SHA1.hexdigest(pass.to_s+salt.to_s)
end

def self.random_string(len)
  #generat a random password consisting of strings and digits
  chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
  newpass = ""
  1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
  return newpass
end

end




